/**
 * Copyright (c) 2006 George Malamidis, nutrun.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * $Author$
 * $Rev$
 */

package aerie.server;

import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetAddress;
import java.io.LineNumberReader;
import java.io.InputStreamReader;

public class Monitor extends Thread {
    private int port = Integer.getInteger("STOP.PORT", -1).intValue();
    private String key = System.getProperty("STOP.KEY", null);

    ServerSocket socket;

    Monitor() {
        try {
            if (port < 0) return;
            setDaemon(true);
            setName("StopMonitor");
            socket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
            if (port == 0) {
                port = socket.getLocalPort();
                System.out.println(port);
            }

            if (key == null) {
                key = Long.toString((long) (Long.MAX_VALUE * Math.random() + this.hashCode() + System.currentTimeMillis()), 36);
                System.out.println("-DSTOP.KEY=" + key);
            }
        }
        catch (Exception e) {
            System.err.println(e.toString());
        }
        if (socket != null) this.start();
        else System.err.println("WARN: Not listening on monitor port: " + port);
    }

    public void run() {
        //noinspection InfiniteLoopStatement
        while (true) {
            Socket socket = null;
            try {
                socket = this.socket.accept();

                LineNumberReader lin = new LineNumberReader(new InputStreamReader(socket.getInputStream()));
                String key = lin.readLine();
                if (!this.key.equals(key)) continue;

                String cmd = lin.readLine();
                if ("stop".equals(cmd)) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        this.socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.exit(0);
                } else if ("status".equals(cmd)) {
                    socket.getOutputStream().write("OK\r\n".getBytes());
                    socket.getOutputStream().flush();
                }
            }
            catch (Exception e) {
                System.err.println(e.toString());
            }
            finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                socket = null;
            }
        }
    }

    /**
     * Start a Monitor.
     * This static method starts a monitor that listens for admin requests.
     */
    public static void monitor() {
        new Monitor();
    }
}
